package com.weifei.core.aop;

import java.lang.reflect.Method;

/**
 * 使用模板设计模式，封装通知公共方法
 */
public class WFAbstractAspectAdvice implements WFAdvice{

    private Method aspectMethod;
    private Object aspectTarget;

    public WFAbstractAspectAdvice(Method aspectMethod, Object aspectTarget) {
        this.aspectMethod = aspectMethod;
        this.aspectTarget = aspectTarget;
    }

    /**
     * 使用反射调用方法
     * @param point
     * @param returnValue
     * @param ex
     * @return
     * @throws Throwable
     */

    public Object invokeAdvice(WFJointPoint point, Object returnValue, Throwable ex)
            throws Throwable {
        Class[] paramsTypes = this.aspectMethod.getParameterTypes();
        if (null == paramsTypes || paramsTypes.length == 0) {
            return this.aspectMethod.invoke(aspectTarget);
        } else {
            Object[] args = new Object[paramsTypes.length];
            for (int i=0; i<paramsTypes.length; i++) {
                if (paramsTypes[i] == WFJointPoint.class) {
                    args[i] = point;
                } else if (paramsTypes[i] == Throwable.class) {
                    args[i] = ex;
                } else if (paramsTypes[i] == Object.class){
                    args[i] = returnValue;
                }
            }
            return this.aspectMethod
                    .invoke(this.aspectTarget, args);

        }
    }
}
